/**
 * Copyright (c) 2020 ~ 2021 KylinSec Co., Ltd.
 * kiran-control-panel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 *
 * Author:     liuxinhao <liuxinhao@kylinsec.com.cn>
 */
#include "advance-settings.h"
#include "config.h"
#include "kiran-tips/kiran-tips.h"
#include "ui_advance-settings.h"
#include "uid-validator.h"

#include <kiran-push-button.h>
#include <kiran-switch-button.h>
#include <QDebug>
#include <QDir>
#include <QEventLoop>
#include <QFileInfo>
#include <QIcon>

AdvanceSettings::AdvanceSettings(QWidget *parent)
    : KiranTitlebarWindow(parent),
      ui(new Ui::AdvanceSettings),
      m_isConfirm(false)
{
    ui->setupUi(getWindowContentWidget());
    initUI();
}

AdvanceSettings::~AdvanceSettings()
{
    delete ui;
}

bool AdvanceSettings::exec(const QString &userName, AdvanceSettingsInfo &info)
{
    AdvanceSettings advanceSettings(nullptr);
    advanceSettings.show();
    advanceSettings.setInfo(userName, info);

    QEventLoop eventLoop;
    connect(&advanceSettings, &AdvanceSettings::sigClose, &eventLoop, &QEventLoop::quit);
    eventLoop.exec();
    if (advanceSettings.isConfirm())
    {
        info = advanceSettings.getInfo();
        return true;
    }

    return false;
}

/// 更新信息
void AdvanceSettings::setInfo(QString userName, const AdvanceSettingsInfo &info)
{
    if (!info.uid.isEmpty())
    {
        m_switchUserID->setChecked(true);
        ui->edit_userID->setText(info.uid);
    }
    else
    {
        m_switchUserID->setChecked(false);
    }

    if (!info.shell.isEmpty())
    {
        ui->edit_loginShell->setText(info.shell);
    }
    else
    {
        ui->edit_loginShell->clear();
        ui->edit_loginShell->setText(ACCOUNT_DEFAULT_SHELL);
    }

    /// 缓存账用户信息，当特殊用户Home目录设置关闭时，重新生成Home目录路径
    m_userName = userName;

    if (!info.homeDir.isEmpty())
    {
        m_switchUserHome->setChecked(true);
        ui->edit_specifyUserHome->setText(info.homeDir);
    }
    else
    {
        m_switchUserHome->setChecked(false);
        ui->edit_specifyUserHome->setText(QString("/home/%1/").arg(m_userName));
    }
}

/// 当点击确定时，创建用户页面获取用户信息
AdvanceSettingsInfo AdvanceSettings::getInfo()
{
    AdvanceSettingsInfo info;
    if (m_switchUserID->isChecked())
    {
        info.uid = ui->edit_userID->text();
    }
    info.shell = ui->edit_loginShell->text();
    if (m_switchUserHome->isChecked())
    {
        info.homeDir = ui->edit_specifyUserHome->text();
    }
    return info;
}

bool AdvanceSettings::isConfirm()
{
    return m_isConfirm;
}

QSize AdvanceSettings::sizeHint() const
{
    return QSize(510, 550);
}

void AdvanceSettings::initUI()
{
    /// 设置窗口模态
    setWindowModality(Qt::ApplicationModal);
    setWindowFlag(Qt::Dialog);
    setWindowFlag(Qt::WindowStaysOnTopHint);

    setTitle(tr("Advance Settings"));
    setIcon(QIcon::fromTheme("user-admin"));
    setResizeable(false);  /// 不可重置大小
    setTitlebarColorBlockEnable(true);

    m_editTip = new KiranTips(this);
    m_editTip->setAnimationEnable(true);
    m_editTip->setShowPosition(KiranTips::POSITION_BOTTM);

    /// shell
    ui->edit_loginShell->setText(ACCOUNT_DEFAULT_SHELL);

    /// user id
    m_switchUserID = new KiranSwitchButton(this);
    ui->layout_specifyUserID->addWidget(m_switchUserID);

    ui->edit_userID->setValidator(new UidValidator(ui->edit_userID));
    ui->edit_userID->setEnabled(false);
    ui->edit_userID->setPlaceholderText(tr("Automatically generated by system"));
    connect(m_switchUserID, &KiranSwitchButton::toggled, [this](bool checked)
            {
        if (checked)
        {
            ui->edit_userID->setEnabled(true);
            ui->edit_userID->setPlaceholderText("");
        }
        else
        {
            ui->edit_userID->setEnabled(false);
            ui->edit_userID->setPlaceholderText(tr("Automatically generated by system"));
            ui->edit_userID->clear();
        } });

    /// home dir
    m_switchUserHome = new KiranSwitchButton(this);
    ui->layout_specifyUserHome->addWidget(m_switchUserHome);
    ui->edit_specifyUserHome->setEnabled(false);
    connect(m_switchUserHome, &KiranSwitchButton::toggled, [this](bool checked)
            {
        if (checked)
        {
            ui->edit_specifyUserHome->setEnabled(true);
        }
        else
        {
            ui->edit_specifyUserHome->setEnabled(false);
            ui->edit_specifyUserHome->setText(QString("/home/%1/").arg(m_userName));
        } });

    /// confirm,cancel
    KiranPushButton::setButtonType(ui->btn_confirm, KiranPushButton::BUTTON_Default);
    connect(ui->btn_confirm, &QPushButton::clicked, [this]()
            {
        QFileInfo fileInfo;
        ///数据校验
        //shell
        QString shellPath = ui->edit_loginShell->text();
        fileInfo.setFile(shellPath);
        if (shellPath.isEmpty() || (!fileInfo.exists()))
        {
            m_editTip->setText(tr("Please enter the correct path"));
            m_editTip->showTipAroundWidget(ui->edit_loginShell);
            return;
        }
        //uid
        if (m_switchUserID->isChecked())
        {
            if (ui->edit_userID->text().isEmpty())
            {
                m_editTip->setText(tr("Please enter specify user Id"));
                m_editTip->showTipAroundWidget(ui->edit_userID);
                return;
            }
            else if (ui->edit_userID->text().toInt() < 1000)
            {
                m_editTip->setText(tr("Please enter an integer above 1000"));
                m_editTip->showTipAroundWidget(ui->edit_userID);
                return;
            }
        }
        //home
        QString homePath = ui->edit_specifyUserHome->text();
        if (homePath.isEmpty())
        {
            m_editTip->setText(tr("Please enter the correct home directory"));
            m_editTip->showTipAroundWidget(ui->edit_specifyUserHome);
            return;
        }
        m_isConfirm = true;
        close(); });

    connect(ui->btn_cancel, &QPushButton::clicked, [this]()
            {
        m_isConfirm = false;
        close(); });
}

void AdvanceSettings::closeEvent(QCloseEvent *event)
{
    emit sigClose();
    KiranTitlebarWindow::closeEvent(event);
}
